<?php


namespace app\admin\controller;

use app\common\model\Attachment;
use app\Request;
use Exception;
use tools\Compress;


class SlicingUploadController extends Controller
{

    protected $save_path = 'uploads/attachment/'; //上传目录
    private  $encoded = "utf-8";
    private $param = [];
    private $chunks = null; //分片总个数
    private $chunk = null; //当前分片
    private $name = null; //当前文件名称
    private $tempName = null; //临时文件名称
    private $time = null;
    private $filePath = null; //合并的文件地址
    protected function initialize()
    {
        parent::initialize();
        $this->param = $this->request->param();
        $this->chunks = isset($this->param['chunks']) ? (int) $this->param['chunks'] : null;
        if ($this->chunks != 0 && !empty($this->chunks)) {
            $this->chunk = (int) $this->param['chunk'];
            if (isset($this->param['name'])) {
                $this->name = iconv($this->encoded, 'GBK//IGNORE', basename($this->param['name']));
                $this->tempName =  $this->chunk . '_' . md5($this->name);
            } else {
                return error('没有文件名称');
            }
            $this->time = time();
            $this->save_path = str_replace("\\", '/', public_path() . $this->save_path . date('Ymd', $this->time));
        }
    }
    public function webuploader(Request $request)
    {
        if ($this->chunks != 0 && !empty($this->chunks)) {

            $file = $request->file('upload');
            $save_path_text = $this->save_path . '/' . $this->name . '/' . $this->tempName . '.part';

            if (!file_exists($save_path_text)) {
                try {
                    $file = $request->file('upload');
                    mkdir_chmod($this->save_path . '/' . $this->name);
                    file_put_contents($save_path_text, file_get_contents($file->getPathname()));
                } catch (Exception $e) {
                    return error($e->getMessage(), '', ['code' => 501],);
                }
            }
            if (isset($this->chunk) && isset($this->chunks) && $this->chunk !== null && $this->chunk == $this->chunks - 1) {
                //合并分片
                $this->fileMerge();
                $pathUrl = explode('public',$this->filePath);
                return success('上传成功', '', ['name'=>$this->name,'url' => $pathUrl[1]]);
            }
        } else {
            $file = $request->file('upload');
            $info = \think\facade\Filesystem::putFile($this->save_path, $file);

            return success($this->name . '上传成功', '', ['name'=>$file->getOriginalName(),'url' => '/' . str_replace("\\", '/',  str_replace("//", '/',  $info))]);
        }
    }
    /**
     * 合并分片
     * @Author: 荷逸
     * @email: 563428234@qq.com
     * @Description
     * @DateTime 2021-07-19
     */
    public function fileMerge()
    {
        $save_path = $this->save_path . '/' . $this->name;
        if (!is_dir($save_path)) {
            return error('切片目录不存在');
        }
        $extArr = explode('.', $this->name);
        $ext = end($extArr);
        $this->filePath =  $this->save_path . '/' . md5($this->time . $this->name) . '.' . $ext;
        if (!$out = fopen($this->filePath, "wb")) {
            return error('创建文件失败,无权限');
        }
        if (flock($out, LOCK_EX)) {
            for ($index = 0; $index < $this->chunks; $index++) {
                while (!file_exists($save_path . '/' . $index . '_' . md5($this->name) . '.part')) {
                    sleep(100);
                }

                if (!$in = fopen($save_path . '/' . $index . '_' . md5($this->name) . '.part', "rb")) {
                    break;
                }
                while ($buff = fread($in, 4096)) {
                    fwrite($out, $buff);
                }
                fclose($in);
                unlink($save_path . '/' . $index . '_' . md5($this->name) . '.part');
            }
            flock($out, LOCK_UN);
        }
        fclose($out);
        rmdir($save_path);
    }
}
